package com.olc.railing.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtils {
    public static final String TAG = "ZipUtils";

    /**
     * 压缩文件和文件夹
     *
     *
     * @param desSdpath
     * @param srcFileString 压缩以后的文件目录
     * @param zipFileString 压缩以后的文件名
     * @throws Exception
     */
    public static void ZipFolder(String desSdpath, String srcFileString, String zipFileString) throws Exception {
        MyLog.d(MyLog.TAG,"desSdpath = "+desSdpath+ " srcFileString = "+srcFileString+" zipFileString = "+zipFileString);
        //创建ZIP
        File file1 = new File(srcFileString+zipFileString);
        MyLog.d(MyLog.TAG,"file1.exists() =="+file1.exists());
        if(!file1.exists()){
            file1.createNewFile();
        }
        ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream( file1));
        //创建文件
        File file = new File(desSdpath);
        //压缩
        ZipFiles(file.getParent() + File.separator, file.getName(), outZip);
        //完成和关闭
        outZip.finish();
        outZip.close();
    }

    /**
     * 压缩文件
     *
     * @param folderString
     * @param fileString
     * @param zipOutputSteam
     * @throws Exception
     */
    private static void ZipFiles(String folderString, String fileString, ZipOutputStream zipOutputSteam) throws Exception {
       // MyLog.d(MyLog.TAG,"folderString:" + folderString + "\n" + "fileString:" + fileString);
        if (zipOutputSteam == null)
            return;
        File file = new File(folderString + fileString);
        if (file.isFile()) {
            ZipEntry zipEntry = new ZipEntry(fileString);
            FileInputStream inputStream = new FileInputStream(file);
            zipOutputSteam.putNextEntry(zipEntry);
            int len;

            byte[] buffer = new byte[512];
            while ((len = inputStream.read(buffer)) != -1) {
               // MyLog.d(MyLog.TAG, "ZipFiles: " + file.getName() + "len:" + len);
                zipOutputSteam.write(buffer, 0, len);
            }
            zipOutputSteam.closeEntry();
        } else {
            //文件夹
            String fileList[] = file.list();
            //没有子文件和压缩
            if (fileList.length <= 0) {
                ZipEntry zipEntry = new ZipEntry(fileString + File.separator);
                zipOutputSteam.putNextEntry(zipEntry);
                zipOutputSteam.closeEntry();
            }
            //子文件和递归
            for (int i = 0; i < fileList.length; i++) {
                ZipFiles(folderString + fileString + "/", fileList[i], zipOutputSteam);
            }
        }
    }
}
